import time
import threading


class Timer:
    def __init__(self, interval=0.01):
        self._interval = interval
        self._running = False
        self._handlers = []
        self._thread = None
        self._real_start_time = None
        self._speed = 1

    @property
    def time(self) -> float:
        if not self._running:
            return 0.0
        else:
            real_interval =  time.perf_counter() - self._real_start_time
            return real_interval * self._speed

    @property
    def speed(self) -> float:
        return self._speed

    @speed.setter
    def speed(self, value: float) -> None:
        if value <= 0:
            raise ValueError(f"speed must >= 0!")
        self._speed = value

    @property
    def is_running(self) -> bool:
        return self._running

    def start(self):
        """启动计时器"""
        if self._running:
            return

        self._real_start_time = time.perf_counter()
        self._running = True
        self._thread = threading.Thread(target=self._loop, daemon=True)
        self._thread.start()

    def stop(self):
        """停止计时器"""
        self._running = False

    def pause(self):
        """暂停计时器"""
        self._running = False

    def add_handler(self, handler):
        """
        添加事件处理函数
        :param handler: 函数，接受零个或多个参数
        """
        if callable(handler):
            self._handlers.append(handler)
        else:
            raise ValueError("Handler must be callable.")

    def _loop(self):
        """定时执行事件检查"""
        while self._running:
            time.sleep(self._interval)


timer = Timer()
timer.start()

while timer.time < 3:
    pass

print(f"{timer.time} end")
timer.stop()